import React from 'react';
import { Table, Input, Popconfirm, Form, Button, message, Spin } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { DividerContainer } from '@/molecules';
import authHelper from '@/utils/auth/helper';
import { Icon } from '../../../components';
import { getInterviewRoundList, addInterviewRound, updateInterviewRound, deleteInterviewRound } from '../../service';
import styles from './index.less';

const { checkCode } = authHelper;

const EditableContext = React.createContext();

const EditItem = props => {
    const { editing, dataIndex, title, record, index, children, ...restProps } = props;
    const context = React.useContext(EditableContext);
    const { form } = context;
    const { getFieldDecorator } = form;

    const getItem = () => (
        <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
                rules: [
                    {
                        required: true,
                        message: `请输入${title}`,
                        whitespace: true
                    }
                ],
                initialValue: (record && record[dataIndex]) || ''
            })(<Input placeholder={`请输入${title}`} maxLength={10} />)}
        </Form.Item>
    );

    const renderCell = () => {
        if (editing) {
            return <td {...restProps}>{getItem()}</td>;
        }

        return <td {...restProps}>{children}</td>;
    };

    return <EditableContext.Consumer>{renderCell}</EditableContext.Consumer>;
};

const RoundTable = ({ form: tempForm }) => {
    const [editingKey, setEditingKey] = React.useState('');

    // 获取面试轮次列表
    const { data, loading, run: fetchRoundList, mutate: setData } = useRequest(getInterviewRoundList, {
        manual: true,
        initialData: [],
        ...defaultFormatResult,
        onSuccess: () => {
            setEditingKey('');
        }
    });

    // 新增面试轮次
    const { run: addRound, loading: addLoading } = useRequest(addInterviewRound, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchRoundList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    // 更新面试轮次
    const { run: updateRound, loading: updateLoading } = useRequest(updateInterviewRound, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchRoundList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    // 删除面试轮次
    const { run: delRound, loading: deleteLoading } = useRequest(deleteInterviewRound, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchRoundList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    const isEditing = record => record.id === editingKey;

    const handleSave = (form, key) => {
        tempForm.validateFields((error, row) => {
            if (error) {
                return;
            }
            if (`${key}`.startsWith('add')) {
                addRound(row);
            } else {
                updateRound({
                    ...row,
                    id: key
                });
            }
        });
    };

    const handleCancel = key => {
        const newData = [...data];
        const index = newData.findIndex(item => key === item.id);
        if (`${key}`.startsWith('add')) {
            newData.splice(index, 1);
            setData(newData);
            setEditingKey('');
        } else {
            setEditingKey('');
        }
    };

    const handleEdit = key => {
        setEditingKey(key);
    };

    const handleDelete = key => {
        delRound(key);
    };

    const handleAdd = () => {
        const newData = [...data];
        const tempKey = `add${new Date().getTime().toString()}`;
        newData.push({
            id: tempKey,
            interviewName: ''
        });
        setData(newData);
        setEditingKey(tempKey);
    };

    React.useEffect(() => {
        fetchRoundList();
    }, []);

    const columns = [
        {
            title: '轮次',
            dataIndex: 'id',
            width: 80,
            render: (text, record, index) => index + 1
        },
        {
            title: '名称',
            dataIndex: 'interviewName',
            editable: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 100,
            render: (text, record) => {
                const editable = isEditing(record);
                return editable ? (
                    <DividerContainer>
                        <EditableContext.Consumer>
                            {form => <Icon title="保存" type="confirm_o" onClick={() => handleSave(form, record.id)} />}
                        </EditableContext.Consumer>
                        <Icon title="取消" type="cancel_o" onClick={() => handleCancel(record.id)} />
                    </DividerContainer>
                ) : (
                    <DividerContainer>
                        {checkCode('office:recruitment:setting:interview:round:update') && (
                            <Icon
                                title="编辑"
                                disabled={editingKey !== ''}
                                type="listfunction_edit_icon_default"
                                onClick={() => handleEdit(record.id)}
                            />
                        )}
                        {checkCode('office:recruitment:setting:interview:round:delete') && (
                            <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
                                <Icon
                                    title="删除"
                                    disabled={editingKey !== ''}
                                    type="listfunction_delete_icon_default"
                                    onClick={() => {}}
                                />
                            </Popconfirm>
                        )}
                    </DividerContainer>
                );
            }
        }
    ];

    const realColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record)
            })
        };
    });

    const components = {
        body: {
            cell: EditItem
        }
    };

    return (
        <EditableContext.Provider value={{ form: tempForm }}>
            <Spin spinning={loading || addLoading || updateLoading || deleteLoading}>
                <Table
                    rowKey="id"
                    bordered={false}
                    components={components}
                    dataSource={data}
                    columns={realColumns}
                    rowClassName={styles.editableRow}
                    pagination={false}
                />
                {checkCode('office:recruitment:setting:interview:round:create') && (
                    <Button
                        type="dashed"
                        icon="plus"
                        block
                        disabled={editingKey !== ''}
                        style={{ marginTop: 12 }}
                        onClick={handleAdd}
                    >
                        添加
                    </Button>
                )}
            </Spin>
        </EditableContext.Provider>
    );
};

export default Form.create()(RoundTable);
